package com.gaussian.property.module.biz.vo.oss;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.songqi.common.core.domain.R;
import com.songqi.common.core.exception.CustomException;
import com.songqi.common.core.utils.uuid.UUID;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;

/**
 * @description:
 * @author: songqi(13776346982)
 * @date: 2024/4/27 20:26
 */
@Data
public class OssConfig {
    private String expiration;

    private String accessKeyId;

    private String accessKeySecret;

    private String securityToken;

    private String requestId;

    private String endPoint;

    private String regionId;

    private String bucket;

    private String objectFileName;

    private static final Logger log = LoggerFactory.getLogger(OssConfig.class);

    public static String getOssFileUrl(String fileObjectName, OssConfig ossConfig) {
        OSS ossClient = ossConfig.createOssClient();
        if(ossClient != null){
            try {
                // 生成URL
                Date expiration = new Date(new Date().getTime() + 9 * 60 * 60 * 1000L);
                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(ossConfig.getBucket(), fileObjectName, HttpMethod.GET);
                generatePresignedUrlRequest.setExpiration(expiration);
                URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
                return url.toString();
            } catch (Exception e){
                log.error(e.getMessage(), e);
                throw new CustomException("oss文件下载失败。请重试");
            } finally {
                ossClient.shutdown();
            }
        }
        return null;
    }

    public boolean uploadFile(InputStream inputStream, String objectName) {
        OSS ossClient = createOssClient();
        if(ossClient != null){
            try {
                PutObjectRequest request = new PutObjectRequest(this.getBucket(), objectName, inputStream);
                PutObjectResult result = ossClient.putObject(request);
                log.info("文件上传结果：{}", JSONUtil.toJsonStr(result));
                return true;
            } catch (Exception e){
                throw new CustomException("文件上传oss失败。请重试");
            } finally {
                ossClient.shutdown();
            }
        }
        return false;
    }



    public boolean uploadFile(File file, String objectName){
        OSS ossClient = createOssClient();
        if(ossClient != null){
            try {
                PutObjectRequest request = new PutObjectRequest(this.bucket, objectName, file);
                PutObjectResult putObjectResult = ossClient.putObject(request);
                return putObjectResult.getResponse().isSuccessful();
            } catch (Exception e){
                throw new CustomException("文件上传oss失败。请重试");
            } finally {
                ossClient.shutdown();
            }
        }
        return false;

    }


    public static void docSnapshot(DocSnapshot docSnapshot, OutputStream outputStream){
        String accessKeyId = docSnapshot.getAccessKeyId();
        String accessKeySecret = docSnapshot.getAccessKeySecret();
        String securityToken = docSnapshot.getSecurityToken();
        String endPoint = docSnapshot.getEndPoint();
        String bucket = docSnapshot.getBucket();
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret, securityToken);
        if(ossClient != null){
            try {
                // 构建文档快照处理指令。
                GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, docSnapshot.getObjectFileName());
                String process = String.format("doc/snapshot,target_png,source_%s,page_%s", docSnapshot.getFileExt(), docSnapshot.getPage());
                getObjectRequest.setProcess(process);

                // 使用getObject方法，并通过process参数传入处理指令。
                OSSObject ossObject = ossClient.getObject(getObjectRequest);

                // 创建输出流到本地文件。
                try (InputStream inputStream = ossObject.getObjectContent()) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                }
            } catch (Exception e){
                throw new CustomException("oss文件快照失败。请重试");
            } finally {
                ossClient.shutdown();
            }
        }
    }


    private OSS createOssClient() {
        OSS ossClient;
        boolean ossConfigInitFlag = CharSequenceUtil.isNotBlank(this.getEndPoint())
                && CharSequenceUtil.isNotBlank(this.getAccessKeyId())
                && CharSequenceUtil.isNotBlank(this.getAccessKeySecret())
                && CharSequenceUtil.isNotBlank(this.getSecurityToken())
                && CharSequenceUtil.isNotBlank(this.getBucket());
        if(ossConfigInitFlag) {
            ossClient = new OSSClientBuilder().build(this.getEndPoint(), this.getAccessKeyId(), this.getAccessKeySecret(), this.getSecurityToken());
        }else {
            throw new CustomException("OssConfig未初始化，请先获取oss配置。");
        }
        return ossClient;
    }

}
